package org.mq.mymq.common.coder;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.ByteToMessageDecoder;
import org.mq.mymq.common.constants.BrokerConstants;

import java.util.List;


/**
 * @ClassName TcpMsgDecoder
 * @Description 消息解码类
 * @Author jiarong_ye
 * @Date 2025/6/19 11:29
 * @Version 1.0
 */
public class TcpMsgDecoder extends ByteToMessageDecoder {
    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf byteBuf, List<Object> list) throws Exception {
        if (byteBuf.readableBytes() > 10) {
            if (byteBuf.readShort() != BrokerConstants.DEFAULT_MAGIC_NUM) {
                ctx.close();
                return;
            }
            int code = byteBuf.readInt();
            int len = byteBuf.readInt();
            int readableByteLen = byteBuf.readableBytes();
            if (byteBuf.readableBytes() > len) {
                ctx.close();
                return;
            }
            byte[] data = new byte[len];
            byteBuf.readBytes(data);
            TcpMsg tcpMsg = new TcpMsg(code, data);
            list.add(tcpMsg);
        }
    }
}
